<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 搜索兰 -->
    <van-search
      v-model="key"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="cellSearch(key)"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 历史记录 -->
    <van-cell-group v-if="!isGroup">
      <van-cell title="历史记录" />
      <van-cell title="123" />
    </van-cell-group>

    <!-- 联想区域 -->
    <van-cell
 
      icon="search"
      v-else
      v-for="(item,index) in colorSearchList"
      :key="index"
    >
      <div v-html="item" ></div>
    </van-cell>
  </div>
</template>

<script>
// 导入获取搜索结果的函数
import { searchListAPI,suggestionListAPI } from "@/api";
export default {
  data() {
    return {
      key: "",
      isGroup: false,
      suggestionList: [],
      time: this.key,
    };
  },
  methods: {
    //   输入内容出发
    cellSearch(key) {
      this.isGroup = true;
      clearTimeout(this.time);
      this.time = setTimeout(async (v) => {
        // 判断输入框是否有值
        if (this.key) {
        //   发起来联想的请求     
        //    page:1, per_page:10,
          let res = await suggestionListAPI({
            q: this.key,
          });
        //   console.log(res);
          // 将获取到的结果赋值给searchList，并渲染数据
          this.suggestionList = res.data.data.options;

        } else {
          this.isGroup = false;
        }
      }, 300);
    },

    // 点击回车或搜索时触发的函数
    onSearch() {
    //   console.log(111);
    //判断传过来的值是否为空
    if(this.key){
        this.$router.push({
            name:'result',
            query:{
                key:this.key
            }
        })

    }
    },
  },
  computed: {
    colorSearchList() {
    //   console.log(this.suggestionList);
      // 遍历搜索联想的数组，产生一个新数组
      let reg = new RegExp(this.key, "ig");
        // console.log(reg);
      return this.suggestionList.map((v) => {
        //   console.log(v);
        return v.replace(reg, `<span style="color:red;">${this.key}</span>`);
      });
    },
  },
};
</script>

<style>
</style>